﻿using Common.Msg;
using Common.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using CToolsWin.DAL;
using CToolsWin.Model;
using Common.Http;
using Model;
using CommonData.Config;

namespace CToolsWin.BLL
{
    public class GrabAddress : CToolsWin.IBLL.IGrab
    {
        #region 获取京东数据之行政区域信息
        private AddressRepository addressRepository = new AddressRepository();
        /// <summary>
        /// 初始化表
        /// </summary>
        public void InitTable()
        {
            //初始化表
            Console.WriteLine("{0} 地址信息表初始化 - -", DateTime.Now);
            addressRepository.InitTable();
            //获取商品分类信息
            Console.WriteLine("{0} 地址信息开始抓取 - -", DateTime.Now);
            Crawler();
        }
        /// <summary>
        /// 爬虫
        /// </summary>
        public void Crawler()
        {
            try
            {
                List<Address> addressList = new List<Address>() {
                    new Address() { ParentId = 0, UnicodeName = StrHelper.StringToUnicodeByCN("中国"), Code = "1", ParentCode = "0", Name = "中国", CreatedTime = DateTime.Now } ,
                    new Address() { ParentId = 0, UnicodeName = StrHelper.StringToUnicodeByCN("海外"), Code = "2", ParentCode = "0", Name = "海外", CreatedTime = DateTime.Now }
                };
                addressRepository.Save(addressList, 1);
                Console.WriteLine("国家数据初始化完成，共抓取地址{0}个", addressList.Count);

                //获取html
                string html = HttpHelper.Get(SystemConfig.AddressRootUrl);

                //解析
                html = html.Substring(html.IndexOf('(') + 1);
                List<BaseAddress> list = Common.Serialize.JsonHelper.ToObject<List<BaseAddress>>(html.Trim(')'));
                addressList = list.Where(b => b.name != "中国" && b.name != "海外").Select<BaseAddress, Address>((b, a) =>
                {
                    if (Regex.IsMatch(b.name, "([\u4e00-\u9fa5])+"))
                    {
                        return new Address() { ParentId = 1, UnicodeName = StrHelper.StringToUnicodeByCN(b.name), Code = b.ID.ToString(), ParentCode = "0", Name = b.name, CreatedTime = DateTime.Now };
                    }
                    else
                    {
                        return new Address() { ParentId = 2, UnicodeName = b.name, Code = b.ID.ToString(), ParentCode = "0", Name = b.name, CreatedTime = DateTime.Now };
                    }
                }).OrderBy(a => Convert.ToInt32(a.Code)).ToList();
                //插入数据库
                addressRepository.Save(addressList, 2);
                Console.WriteLine("省级地址数据初始化完成，共抓取地址{0}个", addressList.Count);
                addressList = addressRepository.QueryList(2);
                foreach (Address add in addressList)
                {
                    List<Address> cityAddressList = GetAddressList(SystemConfig.AddressUrl, add.Code, add.ID);
                    if (cityAddressList != null)
                        addressRepository.Save(cityAddressList, 3);
                    Console.WriteLine("市级地址数据初始化完成，共抓取地址{0}个", cityAddressList.Count);
                    cityAddressList = addressRepository.QueryList(3, add.Code);

                    foreach (Address areaAdd in cityAddressList)
                    {
                        List<Address> areaAddressList = GetAddressList(SystemConfig.AddressUrl, areaAdd.Code, areaAdd.ID);
                        if (areaAddressList != null)
                            addressRepository.Save(areaAddressList, 4);
                        Console.WriteLine("地级地址数据初始化完成，共抓取地址{0}个", areaAddressList.Count);
                    }
                }
                Console.WriteLine("地址数据初始化完成");
            }
            catch (Exception ex)
            {
                Log.GetLog.Error("获取内容出现错误", typeof(GrabAddress), ex);
            }
        }
        public List<Address> GetAddressList(string url, string jdParentCode, long parentId)
        {
            try
            {
                //获取html
                string html = HttpHelper.Get(url + jdParentCode);
                if (string.IsNullOrEmpty(html))
                {
                    Log.GetLog.Warn("获取内容为空,url=" + url + jdParentCode, typeof(GrabAddress));
                }
                //解析
                html = html.Substring(html.IndexOf('(') + 1);
                List<BaseAddress> list = Common.Serialize.JsonHelper.ToObject<List<BaseAddress>>(html.Trim(')'));
                List<Address> addressList = list.Select<BaseAddress, Address>((b, a) =>
                {
                    return new Address() { ParentId = parentId, UnicodeName = StrHelper.StringToUnicodeByCN(b.name), Code = b.ID.ToString(), ParentCode = jdParentCode, Name = b.name, CreatedTime = DateTime.Now };
                }).OrderBy(a => Convert.ToInt32(a.Code)).ToList();
                if (addressList == null || addressList.Count == 0)
                {
                    Log.GetLog.Warn("获取地址数据为空,url=" + url + parentId, typeof(GrabAddress));
                }
                return addressList;
            }
            catch (Exception ex)
            {
                Log.GetLog.Error("获取内容出现错误", typeof(GrabAddress), ex);
            }
            return null;
        }
        #endregion
    }
}
